<template>
  <el-table :data="tableData" border :span-method="objectSpanMethodItem">
    <el-table-column label="岗位" prop="workStationName">
      <template #default="scope">
        {{ scope.row.workStationName }}
        <el-dropdown v-if="parentType != 'view'">
          <span class="el-dropdown-link">
            新增
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleUserSelectAdd(scope.row, scope.$index)">
                新增岗位人员
              </el-dropdown-item>
              <el-dropdown-item @click="handleUserOutAdd(scope.row, scope.$index)">
                新增外包人员
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </el-table-column>
    <el-table-column label="人员" prop="workStationStaffName">
      <template #default="scope">
        <el-input
          v-if="scope.row.isOut"
          v-model="scope.row.workStationStaffName"
          placeholder="请输入外包人员姓名"
          clearable
          @blur="handleUserBlur(scope.row, scope.$index)"
        />
        <span v-else>{{ scope.row.workStationStaffName }}</span>
      </template>
    </el-table-column>
    <el-table-column label="生产工时" prop="prodHours" v-if="isShowProdHours == 'yes'">
      <template #default="scope">
        <el-form-item
          label=" "
          :prop="'tableData.' + tableIndex + '.planGroupMemberList.' + scope.$index + '.prodHours'"
          :rules="{
            required: true,
            message: '生产工时不能为空',
            trigger: ['blur'],
          }"
        >
          <!-- <el-input
            v-model="scope.row.prodHours"
            placeholder="请输入生产工时"
            :disabled="parentType == 'view'"
          ></el-input> -->
          <el-input-number v-model="scope.row.prodHours" :precision="2"></el-input-number>
        </el-form-item>
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center" v-if="parentType != 'view'">
      <template #default="scope">
        <el-button
          link
          type="primary"
          icon="Edit"
          @click="handleUserDelete(scope.row, scope.$index)"
        >
          移除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script name="SubTable" setup>
import { toRefs, getCurrentInstance, computed, watch } from "vue";
const { proxy } = getCurrentInstance();

const tableData = defineModel();
const props = defineProps({
  parentType: {
    type: String,
    default: "view",
  },
  isShowProdHours: {
    type: String,
    default: "no",
  },
  tableIndex: {
    type: Number,
    default: 0,
  },
  prodHoursOriginal: {
    type: Number,
    default: 0,
  },
});
const { parentType, isShowProdHours, tableIndex, prodHoursOriginal } = toRefs(props);

const emit = defineEmits(["addUser", "addOut", "delete"]);

const spanArr = computed(() => {
  const spanCache = [];
  for (let i = 0; i < tableData.value.length; i++) {
    let row = i;
    if (row === 0) {
      spanCache[i] = {
        rowspan: 1,
        colspan: 1,
      };
    } else {
      if (tableData.value[row].workStationName === tableData.value[row - 1].workStationName) {
        let beforeItem = spanCache[row - 1];
        spanCache[row] = {
          rowspan: 1 + beforeItem.rowspan, // 合并几列
          colspan: 1, // 合并几行
        };
        beforeItem.rowspan = 0;
        beforeItem.colspan = 1;
      } else {
        // rowspan 和 colspan 都为1表格此单元格不合并
        spanCache[row] = {
          rowspan: 1,
          colspan: 1,
        };
      }
    }
  }
  let stack = [];
  for (let j = 0; j < tableData.value.length; j++) {
    if (j === 0) {
      if (spanCache[j].rowspan === 0) {
        stack.push(spanCache[j]);
      }
    } else {
      if (spanCache[j].rowspan === 0) {
        stack.push(spanCache[j]);
      } else {
        stack.push(spanCache[j]);
        while (stack.length > 0) {
          let pop = stack.pop();
          let len = stack.length;
          spanCache[j - len] = pop;
        }
      }
    }
  }
  return spanCache;
});
// 因为需要允许手动修改生产工时，所以不能监听tableData表格数据，
// 所以换种思路监听父组件根据开始生产时间和结束生产时间差值变化时才默认回填；
watch(
  prodHoursOriginal,
  (val) => {
    if (val) {
      watchTableData();
    }
  },
  { immediate: true, deep: true }
);

function watchTableData() {
  let _arrNames = [];
  let _newVal = JSON.parse(JSON.stringify(tableData.value));
  for (let i in tableData.value) {
    _arrNames.push(tableData.value[i].workStationStaffName);
  }
  for (let i in tableData.value) {
    let _numCount = findDuplicates(_arrNames)[tableData.value[i].workStationStaffName];
    if (_numCount) {
      let ss = Number(_newVal[i].prodHoursOriginal) / Number(_numCount);
      tableData.value[i].prodHours = ss;
    } else {
      tableData.value[i].prodHours = tableData.value[i].prodHoursOriginal;
    }
  }
}

function findDuplicates(arr) {
  const countMap = {};
  const duplicates = {};

  // 计算每个元素的出现次数
  arr.forEach((item) => {
    if (countMap[item]) {
      countMap[item]++;
    } else {
      countMap[item] = 1;
    }
  });

  // 找出重复的元素及其次数
  Object.keys(countMap).forEach((key) => {
    if (countMap[key] > 1) {
      duplicates[key] = countMap[key];
    }
  });

  return duplicates;
}

function objectSpanMethodItem({ column, rowIndex }) {
  if (column.property === "workStationName") {
    return spanArr.value[rowIndex] || [1, 1];
  }
  return [1, 1];
}

function handleUserSelectAdd(row, index) {
  emit("addUser", { row, index });
}

function handleUserOutAdd(row, index) {
  tableData.value.splice(index, 0, {
    workStationName: row.workStationName,
    workStationCode: row.workStationCode,
    workStationStaffName: "",
    workStationStaff: "",
    isOut: true,
    prodHoursOriginal: prodHoursOriginal.value,
  });
}

function handleUserBlur(row) {
  row.workStationStaffName = row.workStationStaffName + "（外包）";
  watchTableData();
}

// 移除对应岗位人员时进行二次确认
function handleUserDelete(row, index) {
  let _workStationNameArr = tableData.value.map((item) => item.workStationName);
  let _countOccurrences = countOccurrences(_workStationNameArr, row.workStationName);
  if (_countOccurrences == 1) {
    proxy.$modal.msgError("班长、每个岗位至少需要有一名人员！");
    return;
  }
  proxy.$modal
    .confirm("是否确认移除？")
    .then(function () {
      tableData.value.splice(index, 1);
    })
    .then(() => {
      proxy.$modal.msgSuccess("移除成功");
    })
    .catch(() => {});
}
// 获取JavaScript数组中相同值的数量
function countOccurrences(array, value) {
  return array.filter((item) => item === value).length;
}
defineExpose({
  watchTableData,
});
</script>

<style lang="scss" scoped></style>
